package com.sskj.cndragon.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.constraint.Group;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.previewlibrary.GPreviewBuilder;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.shizhefei.view.coolrefreshview.SimpleOnPullListener;
import com.sskj.cndragon.R;
import com.sskj.cndragon.bean.ImgBean;
import com.sskj.cndragon.bean.LastTimeBean;
import com.sskj.cndragon.bean.OrderBuyListBean;
import com.sskj.cndragon.http.HttpConfig;
import com.sskj.cndragon.presenter.OrderBuyDetailActivityPresenter;
import com.sskj.cndragon.view.ToolBarLayout;
import com.sskj.common.base.App;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.ImageUtil;
import com.sskj.common.util.NumberUtil;
import com.sskj.common.util.TimeFormatUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.util.CopyUtil;
import com.sskj.lib.util.TipUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;

public class OrderBuyDetailActivity extends BaseActivity<OrderBuyDetailActivityPresenter> {
    @BindView(R.id.toolbar)
    ToolBarLayout toolbar;
    @BindView(R.id.tv_seller_name)
    TextView tvSellerName;
    @BindView(R.id.tv_dragon_name)
    TextView tvDragonName;
    @BindView(R.id.tv_order)
    TextView tvOrder;
    @BindView(R.id.tv_order_status)
    TextView tvOrderStatus;
    @BindView(R.id.tv_dragon_type)
    TextView tvDragonType;
    @BindView(R.id.tv_days)
    TextView tvDays;
    @BindView(R.id.tv_incomes)
    TextView tvIncomes;
    @BindView(R.id.tv_deal_money)
    TextView tvDealMoney;
    @BindView(R.id.tv_phoenix_money)
    TextView tv_phoenix_money;
    @BindView(R.id.tv_seller_name1)
    TextView tvSellerName1;
    @BindView(R.id.tv_seller_mobile)
    TextView tvSellerMobile;
    @BindView(R.id.iv_copy)
    ImageView ivCopy;
    @BindView(R.id.iv_pay_img)
    ImageView ivPayImg;
    @BindView(R.id.tv_count_down)
    TextView tvCountDown;
    @BindView(R.id.tv_confirm_count_down)
    TextView tv_confirm_count_down;
    @BindView(R.id.tv_msg)
    TextView tvMsg;
    @BindView(R.id.btn_mark_pay)
    Button btnMarkPay;
    @BindView(R.id.group)
    Group group;
    @BindView(R.id.group_confirm_pay_count_down)
    Group group_confirm_pay_count_down;
    @BindView(R.id.group_pay_count_down)
    Group group_pay_count_down;
    @BindView(R.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    @BindView(R.id.tv_wx)
    TextView tvWx;
    @BindView(R.id.iv_copy_wx)
    ImageView ivCopyWx;
    @BindView(R.id.ll_wx)
    LinearLayout llWx;
    @BindView(R.id.tv_ali)
    TextView tvAli;
    @BindView(R.id.iv_copy_ali)
    ImageView ivCopyAli;
    @BindView(R.id.iv_wx)
    ImageView iv_wx;
    @BindView(R.id.iv_ali)
    ImageView iv_ali;
    @BindView(R.id.ll_ali)
    LinearLayout llAli;

    private ImageView mImageView;
    private String mImagePath;

    private String orderID;
    private String imageUrl;//付款图片地址

    private long createTime;
    private long endtime;

    private String wxImg;
    private String aliImg;

    private List<ImgBean> localMedia = new ArrayList<>();

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_order_buy_detail;
    }

    @Override
    public OrderBuyDetailActivityPresenter getPresenter() {
        return new OrderBuyDetailActivityPresenter();
    }

    @Override
    protected void initView() {
        super.initView();
        toolbar.setLeftButtonOnClickListener(view -> finish());
        ClickUtil.click(300, btnMarkPay, () -> markPay(OrderBuyDetailActivity.this));
        ClickUtil.click(300, ivCopy, () -> {
            if (isEmpty(getText(tvSellerMobile))) {
                return;
            }
            CopyUtil.copy(getText(tvSellerMobile));
        });
        ClickUtil.click(300, ivCopyWx, () -> {
            if (isEmpty(getText(tvWx))) {
                return;
            }
            CopyUtil.copy(getText(tvWx));
        });
        ClickUtil.click(300, ivCopyAli, () -> {
            if (isEmpty(getText(tvAli))) {
                return;
            }
            CopyUtil.copy(getText(tvAli));
        });
        ClickUtil.click(300, iv_wx, () -> {
            if (isEmpty(wxImg)) {
                return;
            }
            TipUtil.qrcode(this, HttpConfig.BASE_URL + wxImg);
        });
        ClickUtil.click(300, iv_ali, () -> {
            if (isEmpty(aliImg)) {
                return;
            }
            TipUtil.qrcode(this, HttpConfig.BASE_URL + aliImg);
        });
    }

    @Override
    protected void initData() {
        super.initData();
        orderID = getIntent().getStringExtra(Constans.ORDER_ID);
        if (!isEmpty(orderID)) {
            mPresenter.getOrderDetail(orderID, null);
        }

        coolRefreshView.addOnPullListener(new SimpleOnPullListener() {
            @Override
            public void onRefreshing(CoolRefreshView refreshView) {
                if (isEmpty(orderID)) {
                    return;
                }
                if (localMedia != null) {
                    localMedia.clear();
                }
                mPresenter.getOrderDetail(orderID, coolRefreshView);
            }
        });

        ClickUtil.click(300, ivPayImg, () -> {
            GPreviewBuilder.from(this)//activity实例必须
                    .setData(localMedia)//集合
                    .setCurrentIndex(0)
                    .setSingleFling(false)//是否在黑屏区域点击返回
                    .setDrag(false)//是否禁用图片拖拽返回
                    .setType(GPreviewBuilder.IndicatorType.Dot)//指示器类型
                    .start();//启动
        });
    }

    public AlertDialog markPay(Activity activity) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity, R.style.libDialogBackgroundNull);
        View dialogView = LayoutInflater.from(activity).inflate(R.layout.dialog_mark_pay, null, false);
        builder.setView(dialogView);
        AlertDialog dialog = builder.create();
        dialog.setCancelable(false);
        TextView tv_upload = dialogView.findViewById(R.id.tv_upload);
        mImageView = dialogView.findViewById(R.id.iv_pay_img);
        Button btn_submit = dialogView.findViewById(R.id.btn_submit);
        ClickUtil.click(dialogView.findViewById(R.id.tv_upload), () -> {

            new RxPermissions(OrderBuyDetailActivity.this)
                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                    .subscribe(granted -> {
                        if (granted) {
                            PictureSelector.create(activity)
                                    .openGallery(PictureMimeType.ofImage())
                                    .maxSelectNum(1)
                                    .compress(true)
                                    .minimumCompressSize(100)
                                    .forResult(PictureConfig.CHOOSE_REQUEST);
                        }
                    });
        });
        ClickUtil.click(dialogView.findViewById(R.id.btn_submit), () -> {
            if (isEmpty(imageUrl)) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.appQingxianshangchuanshaitujietu));
                return;
            }
            mPresenter.markPay(orderID);
            dialog.dismiss();
        });
        ClickUtil.click(dialogView.findViewById(R.id.tv_close), () -> {
            dialog.dismiss();
        });
        dialog.show();
        return dialog;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 图片、视频、音频选择结果回调
        if (resultCode == RESULT_OK && requestCode == PictureConfig.CHOOSE_REQUEST) {
            List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
            mImagePath = TextUtils.isEmpty(selectList.get(0).getCompressPath()) ? selectList.get(0).getPath() : selectList.get(0).getCompressPath();

            mPresenter.uploadFile(new File(mImagePath));

        }
    }

    public static void start(Context context, String orderID) {
        Intent intent = new Intent(context, OrderBuyDetailActivity.class);
        intent.putExtra(Constans.ORDER_ID, orderID);
        context.startActivity(intent);
    }

    public void updataOrderDetail(OrderBuyListBean.OrderBuyBean data) {
        if (data == null) {
            return;
        }
        if (isEmpty(data.getWechatAccount())) {
            llWx.setVisibility(View.GONE);
        } else {
            llWx.setVisibility(View.VISIBLE);
            tvWx.setText(data.getWechatAccount());
            wxImg = data.getWechatUrl();
        }
        if (isEmpty(data.getZhifubaoAccount())) {
            llAli.setVisibility(View.GONE);
        } else {
            llAli.setVisibility(View.VISIBLE);
            tvAli.setText(data.getWechatAccount());
            aliImg = data.getZhifubaoUrl();
        }
        createTime = data.getCreateTime();
        tvSellerName.setText(data.getSellUsername());
        tvSellerName1.setText(data.getSellUsername());
        tvDragonName.setText(data.getName());
        tvOrder.setText(data.getSwiftNo());
        tvOrderStatus.setText(data.getStatus() == 1 ? App.INSTANCE.getString(R.string.appDaifukuan) :
                data.getStatus() == 2 ? App.INSTANCE.getString(R.string.appFukaunzhong) :
                        data.getStatus() == 3 ? App.INSTANCE.getString(R.string.appFukuanchenggong) :
                                data.getStatus() == 4 ? App.INSTANCE.getString(R.string.appYiwancheng) :
                                        data.getStatus() == 5 ? App.INSTANCE.getString(R.string.appShensuzhong) :
                                                data.getStatus() == 6 ? App.INSTANCE.getString(R.string.appYiquxiao) : "");
        tvDragonType.setText(data.getName());
        tvDays.setText(data.getContractDays());
        tvIncomes.setText(NumberUtil.keepNoZero(data.getProfitRatio()) + "%");
        tvDealMoney.setText("￥" + NumberUtil.keep2(data.getPrice()));
        tv_phoenix_money.setText(NumberUtil.keep2(data.getPhoenixPrice()) + "FHB");
        tvSellerMobile.setText(data.getSellTel());
        if (data.getStatus() == 1 || data.getStatus() == 2) {
            group.setVisibility(View.GONE);
            group_pay_count_down.setVisibility(View.VISIBLE);
            group_confirm_pay_count_down.setVisibility(View.GONE);
            mPresenter.getLastTime(Constans.BUY);
        } else if (data.getStatus() == 3) {
            group.setVisibility(View.VISIBLE);
            group_pay_count_down.setVisibility(View.GONE);
            group_confirm_pay_count_down.setVisibility(View.VISIBLE);
            btnMarkPay.setVisibility(View.GONE);
            localMedia.add(new ImgBean(data.getPayImgUrl().contains("http") ? data.getPayImgUrl() : HttpConfig.BASE_URL + data.getPayImgUrl()));
            ImageUtil.setImage(data.getPayImgUrl().contains("http") ? data.getPayImgUrl() : HttpConfig.BASE_URL + data.getPayImgUrl(), ivPayImg);
            mPresenter.getLastTime(Constans.SELL);
        } else if (data.getStatus() == 4
                || data.getStatus() == 5
                || data.getStatus() == 6) {
            if (isEmpty(data.getPayImgUrl())) {
                group.setVisibility(View.GONE);
            } else {
                group.setVisibility(View.VISIBLE);
                localMedia.add(new ImgBean(data.getPayImgUrl().contains("http") ? data.getPayImgUrl() : HttpConfig.BASE_URL + data.getPayImgUrl()));
                ImageUtil.setImage(data.getPayImgUrl().contains("http") ? data.getPayImgUrl() : HttpConfig.BASE_URL + data.getPayImgUrl(), ivPayImg);
            }
            group_pay_count_down.setVisibility(View.GONE);
            group_confirm_pay_count_down.setVisibility(View.GONE);
        }
    }

    public void uploadImg(String imgUrl) {
        if (isEmpty(imgUrl)) {
            return;
        }
        mPresenter.uploadPayImg(orderID, imgUrl);
    }

    public void uploadImgOK(String img) {
        if (isEmpty(img)) {
            return;
        }
        imageUrl = img;
        mImageView.setBackgroundColor(Color.parseColor("#161616"));
        ImageUtil.setImage(HttpConfig.BASE_URL + img, mImageView);
    }

    public void markPayOK() {
        mPresenter.getOrderDetail(orderID, null);
    }

    public void getLastTimeOK(LastTimeBean data, int countType) {
        if (data == null) {
            return;
        }
        if (countType == Constans.BUY) {
            endtime = createTime / 1000 + Long.valueOf(data.getPay_time()) * 60;
            long nowTime = System.currentTimeMillis() / 1000;
            if (endtime - nowTime > 0) {
                startTimeDown(endtime - nowTime, tvCountDown);
            }
        }
        if (countType == Constans.SELL) {
            endtime = createTime / 1000 + Long.valueOf(data.getConfirm_time()) * 60;
            long nowTime = System.currentTimeMillis() / 1000;
            if (endtime - nowTime > 0) {
                startTimeDown(endtime - nowTime, tv_confirm_count_down);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (disposableSubscriber != null) {
            if (!disposableSubscriber.isDisposed()) {
                disposableSubscriber.dispose();
                disposableSubscriber = null;
            }
        }
    }

    protected DisposableSubscriber<Long> disposableSubscriber;

    public void startTimeDown(Long totalLong, TextView textView) {
        disposableSubscriber = new DisposableSubscriber<Long>() {
            @Override
            public void onNext(Long aLong) {
                long time = (int) (totalLong - aLong);
                if (tvCountDown != null) {
                    tvCountDown.setText(String.valueOf(time));
                }
                if (textView != null) {
                    textView.setText(TimeFormatUtil.parseTime(time));
                }
                if (time == 1) {
                    mPresenter.getOrderDetail(orderID, null);
                }
            }

            @Override
            public void onError(Throwable t) {
                System.out.println(t.toString());
            }

            @Override
            public void onComplete() {
                if (disposableSubscriber != null) {
                    if (!disposableSubscriber.isDisposed()) {
                        disposableSubscriber.dispose();
                        disposableSubscriber = null;
                    }
                }
            }
        };

        Flowable.interval(0, 1, TimeUnit.SECONDS, Schedulers.newThread())
                .take(totalLong)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(disposableSubscriber);
    }
}
